package com.hyhy.hycloud.uaa.controller;

import com.hyhy.hycloud.commons.constant.HttpHeader;
import com.hyhy.hycloud.commons.dto.InvokeResult;
import com.hyhy.hycloud.uaa.UaaErrorType;
import com.hyhy.hycloud.uaa.dto.CheckVerificationCodeCommand;
import com.hyhy.hycloud.uaa.dto.RequestSignatureResult;
import com.hyhy.hycloud.uaa.dto.SendSmsCodeCommand;
import com.hyhy.hycloud.uaa.exception.BadVerificationCodeException;
import com.hyhy.hycloud.uaa.repository.UserRepository;
import com.hyhy.hycloud.uaa.service.RequestSignatureService;
import com.hyhy.hycloud.uaa.service.UserService;
import com.hyhy.hycloud.uaa.service.VerificationCodeService;
import com.hyhy.hycloud.uaa.util.ImageCaptchaHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录验证码REST API
 *
 * @author Xuegui Yuan
 * @date 2018-09-25
 */
@RequestMapping("/vcode")
@RestController
@Slf4j
public class VerificationCodeController {

    @Autowired
    VerificationCodeService verificationCodeService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserService userService;

    @Autowired
    RequestSignatureService requestSignatureService;

    @GetMapping("/img")
    public void getImageCaptcha(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setDateHeader("Expire", 0);
        new ImageCaptchaHelper().writeNewImageCaptcha(request, response);
    }

    @PostMapping("/img/check/{code}")
    public InvokeResult<?> checkImageCaptcha(@PathVariable(name = "code") String code, HttpSession session) {
        String random = (String) session.getAttribute(ImageCaptchaHelper.RANDOM_CODE_KEY);
        if (random == null || StringUtils.isBlank(code) || !random.equals(code.toUpperCase())) {
            return InvokeResult.success();
        }
        return InvokeResult.error(UaaErrorType.BAD_VERIFICATION_CODE.toRuntimeException());
    }

    @PostMapping("/sms/sendCode")
    public InvokeResult<?> sendSmsVerificationCode(
            @RequestHeader(name = HttpHeader.APP_ID) String appId,
            @RequestBody SendSmsCodeCommand sendSmsCodeCommand) {
        String mobile = sendSmsCodeCommand.getMobile();
        String bizCode = sendSmsCodeCommand.getBizCode();
        userService.checkUserExistByMobile(appId, mobile, bizCode);
        if (userService.getAdminApps().contains(appId)) {
            // 管理类APP验证码返回到前端
            return InvokeResult.success(verificationCodeService
                    .sendSmsVerificationCode(appId, bizCode, mobile));
        }
        verificationCodeService
                .sendSmsVerificationCode(appId, bizCode, mobile);
        return InvokeResult.success();
    }

    @PostMapping("/sms/check")
    public InvokeResult<RequestSignatureResult> checkSmsVerificationCode(
            @RequestBody CheckVerificationCodeCommand checkVerificationCodeCommand) {
        String bizCode = checkVerificationCodeCommand.getBizCode();
        if (!verificationCodeService.checkSmsVerificationCode(bizCode,
                checkVerificationCodeCommand.getMobile(), checkVerificationCodeCommand.getCode())) {
            throw new BadVerificationCodeException();
        }
        String requestId = requestSignatureService.genRequestId();
        return InvokeResult.success(new RequestSignatureResult(requestId,
                requestSignatureService.genSignature(bizCode, requestId)));
    }

}
